import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'messaging_page_controller.dart';
import '../../function/utils/my_common.dart';
import '../../function/state/user_state.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import '../../routes/app_routes.dart';

/// 聊天页面组件
/// 使用非常规命名避免标准模式
class MessagingPage extends GetView<MessagingPageController> {
  const MessagingPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/communal_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: GetX<UserState>(
            builder: (userState) {
              final loggedIn = userState.isLoggedIn;
              if (!loggedIn) {
                return _buildLoggedOutView();
              }
              final userId = userState.currentUser!.id;
              controller.ensureInitedFor(userId);
              return Column(
                children: [_buildTopBar(), Expanded(child: _buildChatList())],
              );
            },
          ),
        ),
      ),
    );
  }

  /// 未登录视图
  Widget _buildLoggedOutView() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 120.w,
          height: 120.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12.r),
            image: DecorationImage(
              image: AssetImage('assets/images/logo.png'),
              fit: BoxFit.contain,
            ),
          ),
        ),
        SizedBox(height: 16.h),
        Text(
          'Log in to view your messages',
          style: TextStyle(fontSize: 16.sp, color: MyCommonUtils.white),
        ),
        SizedBox(height: 12.h),
        Text(
          'Access your chats and never miss updates',
          style: TextStyle(fontSize: 12.sp, color: MyCommonUtils.white),
        ),
        SizedBox(height: 20.h),
        Text('Go to Login')
            .padding(horizontal: 20.w, vertical: 10.h)
            .card(color: MyCommonUtils.white)
            .inkWell(onTap: () => Get.toNamed('/user-access')),
        SizedBox(height: 100.h),
      ],
    );
  }

  /// 顶部信息栏
  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 当前用户头像与昵称
          CircleAvatar(
            radius: 20.w,
            backgroundImage: AssetImage(controller.currentAvatar),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Text(
              controller.currentUsername,
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w700,
                color: MyCommonUtils.white,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  /// 单聊列表
  Widget _buildChatList() {
    final chats = controller.chats;
    if (chats.isEmpty) {
      return Center(
        child: Text(
          'No messages yet',
          style: TextStyle(fontSize: 14.sp, color: MyCommonUtils.white),
        ),
      );
    }

    return MasonryGridView.count(
      crossAxisCount: 1,
      mainAxisSpacing: 0,
      crossAxisSpacing: 0,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      itemCount: chats.length,
      itemBuilder: (context, index) {
        final chat = chats[index];
        final delayMs = 40 * index;
        final item = Column(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 12.h),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  // 头像外环
                  Container(
                    width: 60.w,
                    height: 60.w,
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: MyCommonUtils.orange,
                        width: 2.w,
                      ),
                      image: DecorationImage(
                        image: AssetImage(controller.getOtherAvatar(chat)),
                        fit: BoxFit.cover,
                      ),
                      borderRadius: BorderRadius.circular(24.r),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  // 标题与副标题
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          controller.getOtherDisplayName(chat),
                          style: TextStyle(
                            fontSize: 24.sp,
                            fontWeight: FontWeight.w700,
                            color: MyCommonUtils.white,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(height: 6.h),
                        Text(
                          chat.lastMessage ?? 'Start a conversation',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: MyCommonUtils.white.withValues(alpha: 0.85),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: 12.w),
                  // 右侧时间与未读
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        controller.formatTime(
                          chat.lastMessageTime ?? chat.createTime,
                        ),
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: MyCommonUtils.white,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                      SizedBox(height: 20.h),
                      // if (unread > 0) ...
                    ],
                  ),
                ],
              ),
            ).inkWell(
              onTap: () {
                Get.toNamed(AppRoutes.singleChat, arguments: chat);
              },
            ),
            // 分割线
            Container(
              height: 1.h,
              color: MyCommonUtils.white.withValues(alpha: 0.5),
            ),
          ],
        );

        final isLeft = index.isEven;
        return TweenAnimationBuilder<double>(
          tween: Tween(begin: 0.0, end: 1.0),
          duration: Duration(milliseconds: 600 + delayMs),
          curve: Curves.easeOutCubic,
          builder: (context, value, child) {
            return Opacity(
              opacity: value,
              child: Transform.translate(
                offset: Offset(
                  (isLeft ? -1 : 1) * (1 - value) * 12,
                  (1 - value) * 8,
                ),
                child: child,
              ),
            );
          },
          child: item,
        );
      },
    );
  }
}
